package com.tuanzi.loan.business.service.galaxycard.impl;

import com.tuanzi.loan.business.entity.galaxycard.GalaxyCardPrivilege;
import com.tuanzi.loan.business.entity.galaxycard.GalaxyCardPrivilegeStatus;
import com.tuanzi.loan.business.entity.galaxycard.GalaxyCardRefPrivilege;
import com.tuanzi.loan.business.repository.galaxycard.GalaxyCardPrivilegeStatusJpaRepository;
import com.tuanzi.loan.business.repository.galaxycard.GalaxyCardRefPrivilegeJpaRepository;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.business.repository.galaxycard.GalaxyCardPrivilegeJpaRepository;
import com.tuanzi.loan.business.service.galaxycard.GalaxyCardPrivilegeService;
import com.tuanzi.loan.vo.request.galaxycard.GalaxyCardPrivilegeSearchRequest;
import com.tuanzi.loan.vo.response.galaxycard.GalaxyCardPrivilegeSearchResponse;
import com.tuanzi.loan.business.repository.galaxycard.GalaxyCardPrivilegeRepository;
import com.tuanzi.loan.core.vo.PageSearcher;
import org.springframework.data.domain.Page;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 权益管理 ServiceImplement
 * @author JinRuiyang 2018/2/8 16:26:39
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class GalaxyCardPrivilegeServiceImpl implements GalaxyCardPrivilegeService {

    // 权益状态通用定义
    public enum StatusConst{
        // 未激活
        UN_ACTIVE(0),
        // 已激活
        ACTIVED(1),
        // 激活中-等待用户完善信息（一般为快递信息，也包含业务信息）
        ACTIVING_WAIT_INPUT(5),
        // 激活中-等待快递发货（等待填写快递单号）
        ACTIVING_WAIT_EXPRESS(6),
        // 激活中-快递发货中（填写快递单号后）
        ACTIVING_EXPRESSING(7);

        private int status;
        StatusConst(int status){
            this.status = status;
        }
        public static StatusConst get(int val){
            for (StatusConst status : StatusConst.values()) {
                if (status.val() == val)
                    return status;
            }
            return null;
        }
        public int val() {
            return this.status;
        }
    }

    // 服务器权益点击后的行为参数
    public enum ActionConst{
        // 带Phead跳转新页面
        WEB_VIEW_WITH_PHEAD("launch_vc_webView", "跳转内部新页面"),
        // 不带Phead跳转新页面
        WEB_VIEW_NO_PHEAD("launch_vc_webView", "跳转外部新页面"),
        // 显示Toast | 内容见：toastContent
        TOAST("launch_toast", "显示Toast"),
        // 显示状态页面 | 内容见：statusIconUrl, statusName, statusDescription, statusButtons
        STATUS_PAGE("lunch_status_page", "显示状态页面"),
        // 显示激活码模态框 | 内容见：cdkeyModalTitle, cdkeyModalCode, cdkeyModalGuideUrl, cdkeyModalStatus
        CDKEY_MODAL("lunch_cdkey_modal", "显示激活码模态框");

        private String action;
        private String desc;
        ActionConst(String action, String desc){
            this.action = action;
            this.desc = desc;
        }
        public static ActionConst get(int actionIndex) {
            if (actionIndex >= ActionConst.values().length)
                throw new IllegalArgumentException("actionIndex is invalid");
            return ActionConst.values()[actionIndex];
        }
        public static Map<String, Integer> toMap(){
            Map<String, Integer> map = new HashMap<>();
            for (ActionConst actionConst : values())
                map.put(actionConst.desc, actionConst.ordinal());
            return map;
        }
        public String val(){
            return this.action;
        }
        public String desc() { return this.desc; }
    }

    @Autowired
    private GalaxyCardPrivilegeRepository galaxycardprivilegeRepository;

    @Autowired
    private GalaxyCardPrivilegeJpaRepository galaxycardprivilegeJpaRepository;

    @Autowired
    private GalaxyCardRefPrivilegeJpaRepository galaxyCardRefPrivilegeJpaRepository;

    @Autowired
    private GalaxyCardPrivilegeStatusJpaRepository galaxyCardPrivilegeStatusJpaRepository;

    /**
     * GalaxyCardPrivilege查询
     * @param pageSearcher 请求信息
     * @return 响应列表
     */
    public Page<GalaxyCardPrivilegeSearchResponse> list(PageSearcher<GalaxyCardPrivilegeSearchRequest> pageSearcher) {
        if (Objects.isNull(pageSearcher))
            throw new NullPointerException("pageSearcher is null");
        if (Objects.isNull(pageSearcher.getSearchCondition()) || Objects.isNull(pageSearcher.getPageable()))
            throw new NullPointerException("galaxycardprivilegeSearchRequest or pageable is null");
        return galaxycardprivilegeRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    /**
     * 上架权益
     * @param privilegeId
     * @param cardType
     */
    public void refPrivilegeToCardType(Long privilegeId, Long cardType){
        if (Objects.isNull(privilegeId) || Objects.isNull(cardType))
            throw new IllegalArgumentException("privilegeId or cardType is null");
        GalaxyCardRefPrivilege ref = galaxyCardRefPrivilegeJpaRepository.findByCardTypeAndPrivilegeId(cardType, privilegeId);
        if (Objects.isNull(ref)){
            ref = new GalaxyCardRefPrivilege();
            ref.setCardType(cardType);
            ref.setPrivilegeId(privilegeId);
            galaxyCardRefPrivilegeJpaRepository.save(ref);
        }
        else
            throw new NullPointerException("此卡类型已上架过此权益,上架失败");
    }

    /**
     * 下架权益
     * @param privilegeId
     * @param cardType
     */
    public void unrefPrivilegeToCardType(Long privilegeId, Long cardType){
        if (Objects.isNull(privilegeId) || Objects.isNull(cardType))
            throw new IllegalArgumentException("privilegeId or cardType is null");
        GalaxyCardRefPrivilege ref = galaxyCardRefPrivilegeJpaRepository.findByCardTypeAndPrivilegeId(cardType, privilegeId);
        if (Objects.nonNull(ref)){
            galaxyCardRefPrivilegeJpaRepository.delete(ref);
        }
        else throw new NullPointerException("此卡类型未上架过此权益,下架失败");
    }

    /**
     * 添加权益
     * @param privilege
     */
    public void addPrivilege(GalaxyCardPrivilege privilege){
        if (Objects.isNull(privilege))
            throw new NullPointerException("privilege is null");
        Integer type = privilege.getPrivilegeType();
        Integer count = galaxycardprivilegeRepository.countPrivilegeByType(type);
        privilege.setSort(count + 1);
        privilege.setCreateTime(new Date());
        galaxycardprivilegeJpaRepository.save(privilege);
        Long privilegeId = privilege.getId();
        if (Objects.isNull(privilegeId))
            throw new IllegalStateException("add privilege failed");
        GalaxyCardPrivilegeStatus status0 = getDefaultStatus(privilege.getId());
        galaxyCardPrivilegeStatusJpaRepository.save(status0);
    }

    /**
     * 添加跳转链接类型权益
     * @param privilege
     * @param show
     * @param url
     */
    public void addPrivilege(GalaxyCardPrivilege privilege, String show, String url){
        addPrivilege(privilege);

        GalaxyCardPrivilegeStatus status1 = new GalaxyCardPrivilegeStatus();
        status1.setPrivilegeId(privilege.getId());
        status1.setTarget(url);
        status1.setStatus(StatusConst.ACTIVED.val());
        status1.setShow(show);
        status1.setCreateTime(new Date());
        status1.setAction(ActionConst.WEB_VIEW_NO_PHEAD.ordinal());
        galaxyCardPrivilegeStatusJpaRepository.save(status1);
    }

    @Override
    public GalaxyCardPrivilege findById(Long id) {
        return galaxycardprivilegeJpaRepository.findOne(id);
    }

    @Override
    public void save(GalaxyCardPrivilege privilege) {
        galaxycardprivilegeJpaRepository.save(privilege);
    }

    /**
     * 生成默认权益状态
     * @param privilegeId
     * @return
     */
    private GalaxyCardPrivilegeStatus getDefaultStatus(Long privilegeId){
        GalaxyCardPrivilegeStatus status0 = new GalaxyCardPrivilegeStatus();
        status0.setPrivilegeId(privilegeId);
        status0.setAction(ActionConst.TOAST.ordinal());
        status0.setCreateTime(new Date());
        status0.setShow("等待生效");
        status0.setStatus(StatusConst.UN_ACTIVE.val());
        status0.setTarget("等待生效");
        return status0;
    }

    /**
     * 获取卡类型
     * @return
     */
    @Override
    public Map<String, Long> getCardType() {
        return galaxycardprivilegeRepository.getCardType();
    }
}